package com.junqi.sys.domain.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.junqi.common.entity.AjaxResult;
import com.junqi.common.entity.RedisKeyManager;
import com.junqi.sys.common.utils.JsonUtils;
import com.junqi.sys.common.utils.RedisUtil;
import com.junqi.sys.domain.bo.SysUserBo;
import com.junqi.sys.domain.convert.SysUserBoConvert;
import com.junqi.sys.domain.service.SysUserDomainService;
import com.junqi.sys.infra.basic.entity.SysUser;
import com.junqi.sys.infra.basic.service.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class SysUserDomainServiceImpl implements SysUserDomainService {

    @Resource
    SysUserService sysUserService;

    @Override
    public void updateUserName(String userName) {
        String userId=(String)StpUtil.getLoginId();
        SysUser serviceOne = sysUserService.getById(userId);
        if(userName.equals(serviceOne.getUserName())){
            AjaxResult.errorRun("修改的名字和原有名字不能一样");
        }
        int count = sysUserService.count(new QueryWrapper<SysUser>().eq("user_name", userName));
        if(count>0){
            AjaxResult.errorRun("当前要修改的名字已被使用");
        }
        serviceOne.setUserName(userName);
        serviceOne.setUpdTime(new Date());
        sysUserService.updateById(serviceOne);
    }

    @Override
    public SaTokenInfo doLogin(String code) {
        String openId= RedisUtil.getStr(RedisKeyManager.generateKey(RedisKeyManager.LOGIN_CODE,code));
        if(StrUtil.isBlank(openId)){
            AjaxResult.errorRun("验证码不正确或已失效");
        }
        //注册
        SysUser serviceOne = sysUserService.getOne(new QueryWrapper<SysUser>().eq("wx_open_id", openId).last("limit 1"));
        if(serviceOne==null){
            serviceOne=new SysUser();
            serviceOne.setWxOpenId(openId);
            String num = RandomUtil.randomNumbers(6);
            serviceOne.setUserName("微信用户_"+num);
            serviceOne.setAddTime(new Date());
            serviceOne.setUpdTime(new Date());
            serviceOne.setRoleId("user");
        }
        serviceOne.setLoginTime(new Date());
        sysUserService.saveOrUpdate(serviceOne);
        //redis 记录登录人角色
        RedisUtil.set(RedisKeyManager.generateKey(RedisKeyManager.USER_ROLE,serviceOne.getId()),"user");
        //登录
        StpUtil.login(serviceOne.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return tokenInfo;
    }

    @Override
    public SysUserBo getUserInfo(String userUniqueId) {
        String userId=(String)StpUtil.getLoginId();
        SysUser serviceOne = sysUserService.getById(userId);
        if(serviceOne==null){
            AjaxResult.errorRun("查询不到当前用户信息");
        }
        RedisUtil.set(RedisKeyManager.generateKey(RedisKeyManager.USER_INFO,userUniqueId),serviceOne);
        return SysUserBoConvert.INSTANCE.convertEntityToBO(serviceOne);
    }

    @Override
    public SysUserBo getUserInfoByUserId(String userId) {
        SysUser serviceOne = sysUserService.getById(userId);
        if(serviceOne==null){
            AjaxResult.errorRun("查询不到当前用户信息");
        }
        return SysUserBoConvert.INSTANCE.convertEntityToBO(serviceOne);
    }

    @Override
    public List<Map<String, Object>> getRoomUserList(String id) {
        Set<String> userSet = RedisUtil.sGet(RedisKeyManager.generateKey(RedisKeyManager.ROOM_USERS, id));
        List<Map<String, Object>> list=new ArrayList<>();
        if(CollUtil.isNotEmpty(userSet)){
            for (String userId : userSet) {
                String s = JsonUtils.toObj(userId, String.class);
                SysUser sysUser = RedisUtil.get(RedisKeyManager.generateKey(RedisKeyManager.USER_INFO, s),SysUser.class);
                if(sysUser!=null){
                    Map<String, Object> map=new HashMap<>();
                    map.put("userName",sysUser.getUserName());
                    list.add(map);
                }else{
                    Map<String, Object> map=new HashMap<>();
                    map.put("userName","游客_"+s);
                    list.add(map);
                }
                if(list.size()>50){
                    break;
                }
            }
        }
        return list;
    }
}
